package bainuo

import com.alibaba.fastjson.JSON
import groovy.json.JsonSlurper
import groovy.sql.Sql
import wsd.sys.SST

import java.time.Instant

// 程序入口
def execute(data, dlzt) {
    println "-------------------------待接收物料接口-------------------------"

    // 定义请求地址
    def urlStr = "http://10.1.1.93:9000/bnyy.esb.biz.wms.warehouse.saveInNodeInfo";
    def ClientId = "bnyy.esb.biz.bip"; // ESB平台分配给应用的ID
    def OperationCode = "bnyy.esb.biz.wms.warehouse.saveInNodeInfo"; // ESB平台分配给接口服务操作的编码
    def LoginCode = "sysadmin"; // ESB平台分配给注册应用的用户名
    def LoginPassword = "000000"; // ESB平台分配给注册应用的密码

    try {
        if (data == null) {
            return ["state": 0, "Ascript": "请求参数 data 为空"]
        }

        // 请求信息 校验
        def items = data?.items
        if (items == null || items.isEmpty()) {
            return ["state": 0, "Ascript": "缺少到货单明细行(items) 请求JSON" + data]
        }

        // 遍历每个到货单
        items.each { item ->
            def bill = item?.bill
            if (bill == null) {
                return ["state": 0, "Ascript": "缺少到货单(bill) 请求JSON" + data]
            }

            def id = bill?.id
            def billNo = bill?.billNo
            def billName = bill?.billName
            def billType = bill?.billType
            def supName = bill?.supName
            def constrCorpId = bill?.constrCorpId
            def redBillFlag = bill?.redBillFlag
            def bussUserName = bill?.bussUserName
            def creationtime = bill?.creationtime
            def modifiedtime = bill?.modifiedtime

            if (id == null) {
                return ["state": 0, "Ascript": "缺少到货单ID(id) 请求JSON" + data]
            }
            if (billNo == null) {
                return ["state": 0, "Ascript": "缺少到货单编号(billNo) 请求JSON" + data]
            }
            if (billName == null) {
                return ["state": 0, "Ascript": "缺少到货单名称(billName) 请求JSON" + data]
            }
            if (billType == null) {
                return ["state": 0, "Ascript": "缺少到货类型(billType) 请求JSON" + data]
            }
            if (redBillFlag == null) {
                return ["state": 0, "Ascript": "是否退货(redBillFlag) 请求JSON" + data]
            }

            // 获取到货单明细行
            def detailItems = item?.item
            if (detailItems == null || detailItems.isEmpty()) {
                return ["state": 0, "Ascript": "缺少到货单明细行(detailItems) 请求JSON" + data]
            }

            // 遍历每个明细行
            detailItems.each { detailItem ->
                def ID = detailItem?.id
                def batchNo = detailItem?.batchNo
                def categoryDesc = detailItem?.categoryDesc
                def itemNo = detailItem?.itemNo
                def itemName = detailItem?.itemName
                def itemAlias = detailItem?.itemAlias
                def itemCustomName = detailItem?.itemCustomName
                def itemModel = detailItem?.itemModel
                def cas = detailItem?.cas
                def itemSpec = detailItem?.itemSpec
                def packageNum = detailItem?.packageNum
                def lowLimitWarningValue = detailItem?.lowLimitWarningValue
                def storageConditions = detailItem?.storageConditions
                def projectNo = detailItem?.projectNo
                def itemSource = detailItem?.itemSource
                def manufacturer = detailItem?.manufacturer
                def manufacturerDate = detailItem?.manufacturerDate
                def expectPeriodValidity = detailItem?.expectPeriodValidity
                def remarks = detailItem?.remarks
                def status = detailItem?.status

                if (ID == null) {
                    return ["state": 0, "Ascript": "缺少到货单明细行ID(ID) 请求JSON" + data]
                }
                if (batchNo == null) {
                    return ["state": 0, "Ascript": "缺少批号(batchNo) 请求JSON" + data]
                }
                if (categoryDesc == null) {
                    return ["state": 0, "Ascript": "缺少物料类型(categoryDesc) 请求JSON" + data]
                }
                if (itemNo == null) {
                    return ["state": 0, "Ascript": "缺少物料代码(itemNo) 请求JSON" + data]
                }
                if (itemName == null) {
                    return ["state": 0, "Ascript": "缺少物料名称(itemName) 请求JSON" + data]
                }
                if (cas == null) {
                    return ["state": 0, "Ascript": "缺少CAS(cas) 请求JSON" + data]
                }
                if (packageNum == null) {
                    return ["state": 0, "Ascript": "缺少辅助转换率(packageNum) 请求JSON" + data]
                }
                if (projectNo == null) {
                    return ["state": 0, "Ascript": "缺少项目代号(projectNo) 请求JSON" + data]
                }
                if (status == null) {
                    return ["state": 0, "Ascript": "缺少状态(status) 请求JSON" + data]
                }
            }
        }

        // 调用接口
        def reMap = TransVoucherOpenApi_Create(data, dlzt, ClientId, OperationCode, LoginCode, LoginPassword)
        // 或者使用 HTTP 请求
        // def reMap = bainuo.HQMHttpUtil.httpFWToMap(urlStr, data, ClientId, OperationCode, LoginCode, LoginPassword);

        // 返回接口调用结果
        return reMap
    } catch (Exception e) {
        e.printStackTrace()
        return ["state": 0, "Ascript": "请求参数错误,请检查"]
    }
}

import groovy.json.JsonOutput

def TransVoucherOpenApi_Create(data, dlzt, ClientId, OperationCode, LoginCode, LoginPassword) {
    try {

        def bodyUpList = data.get("items")
        if (bodyUpList == null || bodyUpList.size() == 0) {
            return ["state": 0, "Ascript": "请求参数中待接收物料不能为空"]
        }

        def allResults = [:]

        for (def entry : bodyUpList) {
            def bodyList = entry.get("bill")
            if (bodyList == null || bodyList.size() == 0) {
                allResults=["state": 0, "Ascript": "请求参数中到货单主表表体不能为空"]
                continue
            }

            def bills = [:]
            def BodyObject = ["id": "到货单ID", "billNo": "到货单编号", "billName": "到货单名称", "billType": "到货类型",
                              "supName": "供应商", "bussUserName": "采购员", "constrCorpId": "采购员部门", "redBillFlag": "是否退货", "creationtime": "创建时间",
                              "modifiedtime": "最后修改时间"]
            for(def m:BodyObject.keySet()){
                bills.put(m, bodyList.get(m))
            }

            def items = [:]
            def BodyToObject = ["id": "到货单明细行ID", "batchNo": "批号", "categoryDesc": "物料类型","itemName": "物料名称", "itemNo": "物料代码", "itemAlias": "物料别名",
                                "itemCustomName": "自定义名称", "itemModel": "型号", "cas": "CAS", "itemSpec": "包装规格", "applyNum": "到货辅助数量", "unit": "辅助计量单位", "purchaseNum": "最小单位数量",
                                "packageUnit": "最小计量单位", "unPurchaseNum": "最小单位未到货数量", "applyPrice": "单价", "packageNum": "辅助转换率", "lowLimitWarningValue": "低限预警值",
                                "storageConditions": "贮存条件", "projectNo": "项目代号", "itemSource": "物料来源", "manufacturer": "生产厂家", "manufacturerDate": "生产日期",
                                "expectPeriodValidity": "有效期", "retestDate": "复验期", "remarks": "备注", "status": "状态"]

            // 表体结构
            def RDRecordDetails = []

            // 表体参数循环赋值
            for (def bodyMap : entry.get("item")) {
                if (bodyMap == null || bodyMap.size() == 0) {
                    allResults=["state": 0, "Ascript": "表体数据不能为空"]
                    continue
                }
                def item = [:]
                for (def key : BodyToObject.keySet()) {
                    item.put(key, bodyMap.get(key))
                }
                RDRecordDetails.add(item)
            }

            items.put("bill", bills)
            items.put("item", RDRecordDetails)

            def reMap = HQMHttpUtils.httpFWToMap("http://10.1.1.238:9000/bnyy.esb.biz.wms.material.acceptance", items, ClientId, OperationCode, LoginCode, LoginPassword, dlzt)
            def state = 1
            def msg = ""
            def code = ""
            def success = ""
            def request = reMap.json
            def returnJSON = ""
            if ("1".equals(reMap.get("state").toString())) {
                returnJSON = reMap.data
                def jsonSlurper = new JsonSlurper()
                def dJSON = jsonSlurper.parseText(returnJSON)
                if ("200".equals(dJSON.code.toString())) {
                    state = 1
                    success = "成功"
                } else {
                    state = 0
                    success = "失败"
                }
                code = dJSON.code
                msg = dJSON.message
            } else {
                state = 0
                msg = reMap.msg
                success = "失败"
            }

            def params = [:]
            params.put("code", "'" + code + "'")
            params.put("message", "'" + msg + "'")
            params.put("success", "'" + success + "'")
            params.put("state", state)
            params.put("Ascript", "'" + msg + "'")
            params.put("time", "getdate()")
            params.put("response", "'" + ("调用WMS返回报文=" + returnJSON) + "'") // 添加响应内容

            // 将 data 转换为 JSON 字符串
            def dataStr = JsonOutput.toJson(data)
            params.put("request_data", "'" + dataStr + "'")
            HQMHttpUtils.insertLog(params)

            allResults=["state": state, "Ascript": msg]
        }

        return allResults
    } catch (Exception e) {
        e.printStackTrace()
        return ["state": 0, "Ascript": "操作错误"]
    }
}

class HQMHttpUtils {
    public static HashMap<String, Object> account = new HashMap<String, Object>();

    public HQMHttpUtils() {
    }

    public HQMHttpUtils(HashMap<String, Object> account) {
        this.account = account;
    }

    static def insertLog(params) {
        def conn = null
        try {
            // 创建数据库连接
            conn = Sql.newInstance(SST.hqcon(1))

            // 构建字段名字符串和占位符字符串
            def insertKeys = params.keySet().join(",")
            def placeholders = params.values().collect { "?" }.join(",")

            // 构建插入语句
            def sqlQuery = "INSERT INTO wms_bainuo_log (${insertKeys}) VALUES (${placeholders})"

            // 使用 withStatement 闭包来执行预处理语句
            conn.withStatement { stmt ->
                stmt.execute(sqlQuery, params.values() as List)
            }
        } catch (Exception e) {
            e.printStackTrace()
        } finally {
            if (conn != null) {
                conn.close()
            }
        }
    }

    public static Map httpFWToMap(String url, Map mapdata, String clientId, String operationCode, String loginCode, String loginPassword, dlzt) {

        def returnMap = [:]
        String json = JSON.toJSONString(mapdata);
        println "请求JSON"
        println json
        //PrintWriter out = null;
//        DataOutputStream out
        OutputStream out
        BufferedReader ins = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            HttpURLConnection conn = realUrl.openConnection();
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setRequestMethod("POST");
            conn.setUseCaches(false);
//            conn.setInstanceFollowRedirects(true);
            // 设置通用的请求属性
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setRequestProperty("connection", "Keep-Alive");
//            conn.setRequestProperty("Transfer-Encoding", "chunked");
//            conn.setRequestProperty("Keep-Alive", "chunked");
            conn.setRequestProperty("ClientId", clientId);
            conn.setRequestProperty("OperationCode", operationCode);
            conn.setRequestProperty("LoginCode", loginCode);
            conn.setRequestProperty("LoginPassword", loginPassword);
            conn.connect();
            // 获取HttpURLConnection对象对应的输出流
            //            out = new PrintWriter(conn.getOutputStream());
            //            // 发送请求参数
            //            out.print(json);
            //            // flush输出流的缓冲
            //            out.flush();
            out = conn.getOutputStream();
            if (!"".equals(json)) {
                //out.writeBytes(json);
                out.write(json.getBytes("UTF-8"));
            }
            out.flush();
            out.close();


            // 定义BufferedReader输入流来读取URL的响应
            //            ins = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
            if (conn.getResponseCode() == 200) {
                ins = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
            } else {
                ins = new BufferedReader(new InputStreamReader(conn.getErrorStream(), "UTF-8"));
            }

            String line;
            while ((line = ins.readLine()) != null) {
                result += line;
            }

            def map = new JsonSlurper().parseText(result)
            def now = Instant.now()

            //String SQL = "insert into bainuo_log (code, message, success, state, Ascript, time) values ("+result.code+", ?, ?, ?, ?, ?)"""
            println("调用WMS返回报文=" + result)
//            return JSON.parseObject(result, Map.class);
            returnMap.put("state", "1")
            returnMap.put("msg", "成功")
            returnMap.put("data", result)
        } catch (Exception e) {
            e.printStackTrace();
            //System.out.println("[POST请求]向地址：" + url + " 发送数据：" + json + " 发生错误!" + result + "JSON结束");
            returnMap.put("state", "0")
            returnMap.put("msg", "错误：" + e.getMessage())
            returnMap.put("data", result)
        } finally {// 使用finally块来关闭输出流、输入流
            try {
                if (out != null) {
                    out.close();
                }
                if (ins != null) {
                    ins.close();
                }
            } catch (IOException ex) {
                System.out.println("关闭流异常");
            }
        }
        returnMap.put("json", json)
        return returnMap;
    }
}

